<?php

namespace Bean\Flow;

class FeedFlow extends \Bean\Flow {

	private $_user;
	private $_flows;
	private $_items = array();
	
	public function __construct( \Bean\User $user, $flows ) {
		parent::__construct();
		$this->_flows = $flows;
		$this->_user = $user;
	}

	public function isReadable( \Bean\User $user = null ) {
		$user = _u( $user );
		if( !$user ) {
			return false;
		}
		return $this->_user->is( $user );
	}
	
	public function isWritable( \Bean\User $user = null ) {
		return current($this->_flows)->isWritable( $user );
	}
	
	public function getFlowId() {
		return current($this->_flows)->getFlowId();
	}
	
	public function getGenericId() {
		return current($this->_flows)->getGenericId();
	}
	
	public function getWriter() {
		return current($this->_flows)->getWriter();
	}
	
	public function getItems( $i = 0 ) {
	
		if( !isset($this->_items[ $i ]) ) {
			$items = array();

			foreach( $this->_flows as $flow ) {
				if( $flow->isReadable( _u() ) ) {
					$items = array_merge( $items, $flow->getItems( $i ) );
				}
			}
			usort( $items, array( $this, '_sortByTime' ) );
			if( $items ) {
				$flag = $items;
				$items = array( $prev = current($items) );
				foreach( $flag as $item ) {
					if( $prev->equals( $item ) ) {
						continue;
					}
					$items[] = $prev = $item;
				}
			}
	
			$this->_items[ $i ] = $items;
		}
		return $this->_items[ $i ];
	}
	
	private function _sortByTime( $a, $b ) {
		$a = $a->getPublicationTime();
		$b = $b->getPublicationTime();
		if( $a == $b ) {
			return 0;
		}
		return $a < $b;
	}
}
